package com.lbank.spiderflow.core.utils;

import com.alibaba.fastjson.JSON;
import com.lbank.spiderflow.core.io.HttpRequest;
import com.lbank.spiderflow.core.io.HttpResponse;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class HttpClientHelper {

    public static String send(String url) {
        return send(url, "GET", null, null, false);
    }

    public static String send(String url, String method) {
        return send(url, method, null, null, false);
    }

    public static String send(String url, String method, Map<String, String> headers) {
        return send(url, method, headers, null, false);
    }

    public static String send(String url, String method,
                              Map<String, String> headers,
                              Map<String, Object> parameters,
                              boolean isBody
    ) {

        HttpRequest request = HttpRequest.create();
        request.url(url);
        request.method(method);
        request.followRedirect(true);
        if (Objects.nonNull(headers)) {
            headers.keySet().forEach(header -> {
                request.header(header, headers.get(header));
            });
        }

        if (isBody) {
            request.contentType("application/json");
            if (Objects.nonNull(parameters)) {
                request.data(JSON.toJSON(parameters));
            }
        } else {
            if (Objects.nonNull(parameters)) {
                parameters.keySet().forEach(parameter -> {
                    request.data(parameter, parameters.get(parameter));
                });
            }
        }

        HttpResponse execute = null;
        try {
            execute = request.execute();
        } catch (IOException e) {
            LogHelper.error("request execute error ,url={}", url, e);
        }
        LogHelper.info("url:{}", execute.getUrl());
        return Objects.nonNull(execute) ? execute.getHtml() : "";
    }
}
